//
//  RootViewController.m
//  MobileSail
//
//  Created by Roy Brown on 8/8/09.
//  Copyright __MyCompanyName__ 2009. All rights reserved.
//

#import "RootViewController.h"
#import "MobileSailAppDelegate.h"

/*@interface RootViewController : UIViewController <UITextFieldDelegate> 
{
	userInput.delegate = self;
}
@end*/

@implementation RootViewController

@synthesize userInput, passwordInput, myLabel, greeting, webData, soapResults, xmlParser, mainMenuViewController;

-(IBAction)Connect_Click:(id)sender 
{
	[self callWebService];
	
	if (myLabel.text != @"x18")
	{
		if (self.mainMenuViewController == nil)
		{
			MainMenuViewController *mainmenu = [[MainMenuViewController alloc] initWithNibName:@"MainMenu" bundle:[NSBundle mainBundle]];
			self.mainMenuViewController = mainmenu;
			[mainmenu release];
		}
	
		[self.navigationController pushViewController:self.mainMenuViewController animated:YES];
	
	}
}

- (BOOL)dismissKeyBoard:(id)sender
{
	[sender resignFirstResponder];
	return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
	self.title = @"Logon";
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void) callWebService
{
	[myLabel setText:@"starting web service call"];
	
	recordResults = FALSE;
	
	NSString *soapMessage = [NSString stringWithFormat:
							 @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
							 "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
							 "<soap:Body>\n"
							 "<Hello xmlns=\"http://viium.com/\">\n"
							 "<name>%@</name>\n"
							 "</Hello>\n"
							 "</soap:Body>\n"
							 "</soap:Envelope>\n", userInput.text
							 ];
	
	NSLog(soapMessage);
	
	NSURL *url = [NSURL URLWithString:@"http://viium.com/WebService/HelloWorld.asmx"];
	
	NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
	
	NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
	
	[theRequest addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
	[theRequest addValue:@"http://viium.com/Hello" forHTTPHeaderField:@"SOAPAction"];
	[theRequest addValue:msgLength forHTTPHeaderField:@"Content-Length"];
	[theRequest setHTTPMethod:@"POST"];
	[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
	
	NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
	
	if ( theConnection )
	{
		//[myLabel setText:@"x1"];
		webData = [[NSMutableData data] retain];
	}
	else
	{
		//[myLabel setText:@"x2"];
		NSLog(@"theConnection is NULL");
	}
	
	//[myLabel setText:@"x19"];
	
	[userInput resignFirstResponder];
	
	//[myLabel setText:@"x20"];
}

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	//[myLabel setText:@"x3"];
	[webData setLength: 0];
}

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	//[myLabel setText:@"x4"];
	[webData appendData: data];
}

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	//[myLabel setText:@"x5"];
	NSLog(@"ERROR with theConnection");
	[connection release];
	[webData release];
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
	//[myLabel setText:@"x6"];
	
	NSLog(@"DONE. Received Bytes: %d", [webData length]);
	
	//[myLabel setText:@"x7"];
	
	NSString *theXml = [[NSString alloc] initWithBytes: [webData mutableBytes] length: [webData length] encoding:NSUTF8StringEncoding];
	
	//[myLabel setText:@"x8"];
	
	NSLog(theXml);
	
	//[myLabel setText:@"x9"];
	
	[theXml release];
	
	if ( xmlParser )
	{
		//[myLabel setText:@"x10"];
		[xmlParser release];		
	}
	else
	{
		//[myLabel setText:@"x11"];
	}
	
	xmlParser = [[NSXMLParser alloc] initWithData: webData];
	
	[xmlParser setDelegate:self];
	[xmlParser setShouldResolveExternalEntities:YES];
	[xmlParser parse];
	
	[connection release];
	[webData release];	
}

- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qname attributes:(NSDictionary *)attributeDict
{
	//[myLabel setText:@"x12"];
	
	if ([elementName isEqualToString:@"HelloResult"])
	{
		//[myLabel setText:@"x13"];
		if(!soapResults)
		{
			//[myLabel setText:@"x14"];
			soapResults = [[NSMutableString alloc] init];
			
		}		
		recordResults = TRUE;
		//[myLabel setText:@"x15"];
	}
}

- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 
{
	//[myLabel setText:@"x16"];
	if (recordResults)
	{
		//[myLabel setText:@"x17"];
		[soapResults appendString: string];
	}
}

- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qname
{
	[myLabel setText:@"x18"];
	if ([elementName isEqualToString:@"HelloResult"])
	{
		recordResults = FALSE;
		greeting.text = (NSXMLParser *)soapResults;
		[soapResults release];
		soapResults = nil;
	}
}

/*
- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
*/

/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


- (void)dealloc {
    [super dealloc];
}


@end

